var fileIndex = 1;
// 全局配置对象
var config = null;
var currentApi = null;
var secretLevel = null;

// 在文件顶部添加存储响应数据的对象
var apiResponses = {};
// 添加一个变量来跟踪从 getTaskStatus 页面发起的查询
var taskStatusQueries = new Set();

// 参数表格生成相关函数
function generateParamsTable(params) {
    if (!params || !params.length) {
        return '<p class="no-params">无参数</p>';
    }

    return '<table class="parameter-table">' +
               '<thead>' +
                   '<tr>' +
                       '<th>参数名</th>' +
                       '<th>类型</th>' +
                       '<th>必填</th>' +
                       '<th>说明</th>' +
                   '</tr>' +
               '</thead>' +
               '<tbody>' +
                   generateParamsRows(params) +
               '</tbody>' +
           '</table>';
}

function generateParamsRows(params, prefix) {
    // 设置默认值
    prefix = prefix || '';

    return params.map(function(param) {
        var rows = '<tr>' +
                   '<td>' + prefix + param.name + '</td>' +
                   '<td>' + param.type + '</td>' +
                   '<td>' + (param.required ? '是' : '否') + '</td>' +
                   '<td>' + (param.description || '') + '</td>' +
               '</tr>';

        // 处理数组类型的子参数
        if (param.type === 'array' && param.children) {
            rows += param.children.map(function(child) {
                return '<tr>' +
                       '<td>' + prefix + param.name + '[].' + child.name + '</td>' +
                       '<td>' + child.type + '</td>' +
                       '<td>' + (child.required ? '是' : '否') + '</td>' +
                       '<td>' + (child.description || '') + '</td>' +
                   '</tr>';
            }).join('');
        }

        // 处理对象类型的子参数
        if (param.type === 'object' && param.children) {
            rows += generateParamsRows(param.children, prefix + param.name + '.');
        }

        return rows;
    }).join('');
}

// 示例生成函数
function generateExamples(examples) {
    if (!examples) return '<p class="no-examples">暂无示例</p>';

    var html = '';

    if (examples.request) {
        html += '<div class="example-section"><h5>请求示例：</h5><pre class="example-code"><code>' + JSON.stringify(examples.request, null, 2) + '</code></pre></div>';
    }

    if (examples.success) {
        html += '<div class="example-section"><h5>成功响应示例：</h5><pre class="example-code"><code>' + JSON.stringify(examples.success, null, 2) + '</code></pre></div>';
    }

    if (examples.failure) {
        html += '<div class="example-section"><h5>失败响应示例：</h5><pre class="example-code"><code>' + JSON.stringify(examples.failure, null, 2) + '</code></pre></div>';
    }

    return html || '<p class="no-examples">暂无示例</p>';
}

// 表单生成相关函数
function generateForm(params) {
    if (!params || !params.length) {
        return '<p>无需填写参数</p>';
    }
    return generateFormFields(params).join('');
}

function generateFormFields(params, prefix) {
    // 设置默认值
    prefix = prefix || '';

    return params.map(function(param) {
        // 对象类型参数
        if (param.type === 'object') {
            var childrenHtml = '';
            var fieldId = (prefix + param.name).replace(/[\[\]\.]/g, '_');
            var fieldName = prefix + param.name;

            // 特殊处理 taskID 参数
            if (param.name === 'taskID' && param.stype === 'status') {
                return '<fieldset class="form-group-object">' +
                    '<legend>任务ID</legend>' +
                    '<div class="taskids-container">' +
                    '<div class="taskids-container-body">' +
                    '<div class="taskid-entry" data-index="0">' +
                    '<div class="form-group required-field">' +
                    '<div class="input-container d-flex align-items-center">' +
                    '<input type="text" ' +
                    'name="taskID[]" ' +
                    'id="' + fieldId + '_0" ' +
                    'required ' +
                    'class="flex-grow-1" ' +
                    'placeholder="请输入任务ID" ' +
                    'oninput="validateTaskId(this)" ' +
                    'onblur="validateTaskId(this)" />' +
                    '</div>' +
                    '<div class="error-message"></div>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '</fieldset>';
            }

            // 特殊处理 authjson 对象
            if (param.name === 'authJson') {
                childrenHtml = '<div class="auth-json-container">' +
                               '<div class="auth-json-section">' +
                                   '<h4>文件认证信息</h4>' +
                                   '<div class="form-group ' + (param.required ? 'required-field' : '') + '">' +
                                       '<label for="' + fieldId + '_file_SN">认证信息第一部分:</label>' +
                                       '<div class="input-container">' +
                                           '<input type="text" ' +
                                                  'name="' + fieldName + '.file.SN" ' +
                                                  'id="' + fieldId + '_file_SN" ' +
                                                  'required />' +
                                       '</div>' +
                                   '</div>' +
                                   '<div class="form-group ' + (param.required ? 'required-field' : '') + '">' +
                                       '<label for="' + fieldId + '_file_SN2">认证信息第二部分:</label>' +
                                       '<div class="input-container">' +
                                           '<input type="text" ' +
                                                  'name="' + fieldName + '.file.SN2" ' +
                                                  'id="' + fieldId + '_file_SN2" ' +
                                                  'required />' +
                                       '</div>' +
                                   '</div>' +
                               '</div>' +
                           '</div>' +
                           '<div class="form-group ' + (param.required ? 'required-field' : '') + '">' +
                               '<label for="' + fieldId + '_code">解密口令:</label>' +
                               '<div class="input-container">' +
                                   '<input type="text" ' +
                                          'name="' + fieldName + '.code" ' +
                                          'id="' + fieldId + '_code" ' +
                                          'required />' +
                               '</div>' +
                           '</div>';
            } else {
                // 其他对象的常规处理
                childrenHtml = param.children.map(function(child) {
                    var childId = fieldId + '_' + child.name;
                    return '<div class="form-group ' + (child.required ? 'required-field' : '') + '">' +
                               '<label for="' + childId + '">' + child.description + ':</label>' +
                               '<div class="input-container">' +
                                   (child.name === 'level' ? '<select name="' + fieldName + '.' + child.name + '" ' +
                                                                 'id="' + childId + '" ' +
                                                                 (child.required ? 'required' : '') + '>' +
                                       '<option value="">请选择密级</option>' +
                                       secretLevel.map(function(level) {
                                           return '<option value="' + level.value + '">' + level.label + '</option>';
                                       }).join('') +
                                   '</select>' : '<input type="text" ' +
                                                   'name="' + fieldName + '.' + child.name + '" ' +
                                                   'id="' + childId + '" ' +
                                                   (child.required ? 'required' : '') + ' />') +
                               '</div>' +
                           '</div>';
                }).join('');
            }

            return '<div class="form-group-object">' +
                       '<label>' + (param.description || param.name) + ':</label>' +
                       childrenHtml +
                   '</div>';
        }

        // 基础类型参数
        return generateFormField(param, prefix);
    });
}

function generateFormField(param, prefix) {
    var fieldName = prefix + param.name;
    var fieldId = fieldName.replace(/[\[\]\.]/g, '_');

    // Special handling for taskID
    if (param.name === 'taskID' && param.stype === 'status') {
        return '<fieldset class="form-group-object">' +
            '<legend>任务ID列表</legend>' +
            '<div class="taskids-container">' +
            '<div class="taskids-container-body">' +
            '<div class="taskid-entry" data-index="0">' +
            '<div class="form-group required-field">' +
            '<div class="input-container d-flex align-items-center">' +
            '<input type="text" ' +
            'name="taskID[]" ' +
            'id="' + fieldId + '_0" ' +
            'required ' +
            'class="flex-grow-1" ' +
            'placeholder="请输入任务ID" ' +
            'oninput="validateTaskId(this)" ' +
            'onblur="validateTaskId(this)" />' +
            '</div>' +
            '<div class="error-message"></div>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</fieldset>';
    }

    // Special handling for files array
    if (param.name === 'files') {
        return '<fieldset class="form-group-object">' +
                   '<legend>' + (param.description || param.name) + '</legend>' +
                   '<div class="files-container">' +
                       '<div class="files-container-header">' +
                           '<h4>文件信息</h4>' +
                       '</div>' +
                       '<div class="files-container-body">' +
                           '<div class="file-entry" data-index="0">' +
                               '<div class="file-entry-grid">' +
                                   param.children.map(function(child) {
                                       var index = 0; // 初始索引
                                       return '<div class="form-group ' + (child.required ? 'required-field' : '') + '">' +
                                           '<label for="' + fieldId + '_' + index + '_' + child.name + '">' + child.description + ':</label>' +
                                           '<div class="input-container">' +
                                               (child.placeholder ? '<div class="field-tip">' + child.placeholder + '</div>' : '') +
                                               (child.name === 'sl' ? '<select name="files[' + index + '].' + child.name + '" ' +
                                                                     'id="' + fieldId + '_' + index + '_' + child.name + '" ' +
                                                                     'class="sl-select" ' +  // 添加类名以便后续操作
                                                                     (child.required ? 'required' : '') + '>' +
                                                   '<option value="">请选择密级</option>' +
                                                   secretLevel.map(function(level) {
                                                       return '<option value="' + level.value + '">' + level.label + '</option>';
                                                   }).join('') +
                                               '</select>' : '<input type="text" ' +
                                                               'name="files[' + index + '].' + child.name + '" ' +
                                                               'id="' + fieldId + '_' + index + '_' + child.name + '" ' +
                                                               'class="file-input" ' +  // 添加类名以便后续操作
                                                               'placeholder="' + (child.placeholder || '') + '" ' +
                                                               (child.required ? 'required' : '') + ' />') +
                                           '</div>' +
                                       '</div>';
                                   }).join('') +
                               '</div>' +
                               '<button type="button" class="remove-file-btn" style="display: none;"></button>' +
                           '</div>' +
                       '</div>' +
                       '<div class="files-container-footer">' +
                            '<div class="button-group">' +
                                '<button type="button" class="btn add-file-btn">添加文件</button>' +
                                '<div class="import-file-container">' +
                                    '<input type="file" id="xmlFileInput" accept=".xml" style="display: none;">' +
                                    '<button type="button" class="btn import-file-btn" onclick="document.getElementById(\'xmlFileInput\').click()">导入XML</button>' +
                                '</div>' +
                            '</div>' +
                        //    '<button type="button" class="btn add-file-btn">添加文件</button>' +
                        //    '<div class="import-file-container">' +
                        //        '<input type="file" id="xmlFileInput" accept=".xml" style="display: none;">' +
                        //        '<button type="button" class="btn import-file-btn" onclick="document.getElementById(\'xmlFileInput\').click()">导入XML</button>' +
                        //    '</div>' +
                       '</div>' +
                   '</div>' +
               '</fieldset>';
    }

    // Special handling for discJson object
    if (param.name === 'discJson') {
        return '<div class="form-group ' + (param.required ? 'required-field' : '') + '">' +
                   '<label>' + (param.description || param.name) + ':</label>' +
                   '<div class="disc-json-container">' +
                       '<div class="disc-json-header">' +
                           '<h4>载体信息</h4>' +
                       '</div>' +
                       '<div class="disc-json-body">' +
                           param.children.map(function(child) {
                               return '<div class="form-group ' + (child.required ? 'required-field' : '') + '">' +
                                   '<label for="' + fieldId + '_' + child.name + '">' + child.description + ':</label>' +
                                   '<div class="input-container">' +
                                       '<input type="' + (child.type === 'number' ? 'number' : 'text') + '" ' +
                                              'name="discJson.' + child.name + '" ' +
                                              'id="' + fieldId + '_' + child.name + '" ' +
                                              (child.required ? 'required' : '') + ' />' +
                                   '</div>' +
                               '</div>';
                           }).join('') +
                       '</div>' +
                   '</div>' +
               '</div>';
    }

    // Regular input fields for other parameters
    return '<div class="form-group ' + (param.required ? 'required-field' : '') + '">' +
               '<label for="' + fieldId + '">' + (param.description || param.name) + ':</label>' +
               '<div class="input-container">' +
                   (param.placeholder ? '<div class="field-tip">' + param.placeholder + '</div>' : '') +
                   '<input type="text" ' +
                          'name="' + fieldName + '" ' +
                          'id="' + fieldId + '" ' +
                          'placeholder="' + (param.placeholder || '') + '" ' +
                          (param.required ? 'required' : '') + ' />' +
               '</div>' +
           '</div>';
}

// 添加XML文件处理函数
function handleXMLFile(file) {
    const reader = new FileReader();
    reader.onload = function(e) {
        try {
            const parser = new DOMParser();
            const xmlDoc = parser.parseFromString(e.target.result, "text/xml");
            const fileNodes = xmlDoc.getElementsByTagName("file");
            
            // 清除现有的文件条目
            $('.file-entry').not(':first').remove();
            
            // 遍历XML中的文件节点
            Array.from(fileNodes).forEach((fileNode, index) => {
                if (index > 0) {
                    // 点击添加文件按钮创建新条目
                    $('.add-file-btn').click();
                }
                
                // 获取当前文件条目
                const $fileEntry = $('.file-entry').eq(index);
                
                // 填充表单字段
                $fileEntry.find('input, select').each(function() {
                    const fieldName = this.name.split('.').pop();
                    const value = fileNode.getAttribute(fieldName) || '';
                    $(this).val(value);
                });
            });
        } catch (error) {
            console.error('XML解析错误:', error);
            alert('XML文件解析失败，请检查文件格式是否正确');
        }
    };
    reader.readAsText(file);
}

// 绑定文件输入事件
$(document).on('change', '#xmlFileInput', function(e) {
    const file = e.target.files[0];
    if (file) {
        if (file.type === "text/xml" || file.name.endsWith('.xml')) {
            handleXMLFile(file);
        } else {
            alert('请选择XML文件');
        }
        // 清除文件输入，允许重复选择同一文件
        this.value = '';
    }
});

// API内容生成函数
function generateApiContent(api) {
    return '<div class="endpoint-section">' +
               '<div class="api-docs">' +
                   // API基本信息
                   '<div class="api-info">' +
                       '<span class="api-method ' + api.method.toLowerCase() + '">' + api.method + '</span>' +
                       '<span class="api-path">' + api.path + '</span>' +
                       (api.id === 'getTaskStatus' ? '<span class="api-thread-status">|</span>' : '') +
                   '</div>' +

                   // API描述
                   '<div class="api-description">' +
                       '<h4>接口说明</h4>' +
                       '<p>' + (api.description || '暂无说明') + '</p>' +
                   '</div>' +

                   // 请求参数 (非getTaskStatus时显示)
                   (api.id !== 'getTaskStatus' ? 
                   '<div class="api-params">' +
                       '<h4>请求参数</h4>' +
                       '<div class="request-params">' +
                           generateParamsTable(api.requestParams) +
                       '</div>' +
                   '</div>' : '') +

                   // 响应参数 (非getTaskStatus时显示)
                   (api.id !== 'getTaskStatus' ? 
                   '<div class="api-response">' +
                       '<h4>响应参数</h4>' +
                       '<div class="response-params">' +
                           generateParamsTable(api.responseParams) +
                       '</div>' +
                   '</div>' : '') +

                   // 示例 (非getTaskStatus时显示)
                   (api.id !== 'getTaskStatus' ? 
                   '<div class="api-examples">' +
                       '<h4>示例</h4>' +
                       '<div class="example-content">' +
                           generateExamples(api.examples) +
                       '</div>' +
                   '</div>' : '') +
               '</div>' +

               // 接口测试区域
               '<div class="api-test-section">' +
                   (api.id === 'getTaskStatus' ?
                   '<div class="thread-status-container">' +
                       '<div class="thread-progress-bar">' +
                           '<div class="thread-progress"></div>' +
                       '</div>' +
                       '<div class="thread-status-text">线程使用情况: 0/10 (0.0%)</div>' +
                    '</div>' : '') +
                   '<h4>接口测试</h4>' +
                   '<form class="api-form">' +
                       '<div class="form-content">' +
                           generateForm(api.requestParams) +
                       '</div>' +
                       '<div class="form-actions">' +
                           '<button type="button" class="btn blue_btn submit-btn">发送请求</button>' +
                           '<button type="reset" class="btn white_btn">重置</button>' +
                       '</div>' +
                   '</form>' +

                   (api.id !== 'getTaskStatus' ?
                   '<div class="request-response-info">' +
                       '<div class="request-section">' +
                           '<h4>请求数据</h4>' +
                           '<pre class="request-data"></pre>' +
                       '</div>': '' ) +
                       '<div class="response-section">' +
                           '<h4>响应数据</h4>' +
                           (api.id === 'getTaskStatus' ?
                            '<div class="table-header">' +
                                '<button type="button" class="btn btn-danger clear-table-btn">清空表格</button>' +
                            '</div>' +
                            '<div class="response-table-container">' +
                                '<table class="response-table">' +
                                '<thead>' +
                                '<tr>' +
                                '<th>任务ID</th>' +
                                '<th>状态</th>' +
                                '<th>总文件数</th>' +
                                '<th>已完成数</th>' +
                                '<th class="progress-column">进度</th>' +
                                '<th>开始时间</th>' +
                                '<th>耗时</th>' +
                                '<th>错误信息</th>' +
                                '</tr>' +
                                '</thead>' +
                                '<tbody></tbody>' +
                                '</table>' +
                            '</div>' : '') +
                            '<pre class="response-data"' + (api.id === 'getTaskStatus' ? ' style="display: none;"' : '') + '></pre>' +
                            '</div>' +
                   '</div>' +
               '</div>' +
           '</div>';
}

// 页面初始化相关函数
function loadConfig() {
    $.ajax({
        url: './config/config.json',
        dataType: 'json',
        cache: false,
        success: function(data) {
            config = data;
            secretLevel = config.secretLevel || [];
            initializePage();
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.error('配置加载失败:', {
                status: jqXHR.status,
                statusText: jqXHR.statusText,
                responseText: jqXHR.responseText
            });
            showErrorMessage('配置文件加载失败，请检查网络连接或刷新页面重试');
        }
    });
}

function initializePage() {


    // 设置页面标题
    $('.page-header h1').text(config.pageTitle);

    // 生成侧边栏菜单
    generateSidebar();

    // 默认显示第一个接口
    if (config.apis.length > 0) {
        showApiDetails(config.apis[0].id);
    }

    // 添加菜单按钮和遮罩层
    if (!$('.menu-toggle').length) {
        $('body').prepend('<button class="menu-toggle"><svg viewBox="0 0 24 24" width="24" height="24"><path fill="currentColor" d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"/></svg></button><div class="sidebar-overlay"></div>');
    }

    // 绑定菜单按钮点击事件
    $('.menu-toggle').off('click').on('click', function() {
        $('.sidebar').toggleClass('active');
        $('.sidebar-overlay').toggleClass('active');
    });

    // 点击遮罩层关闭菜单
    $('.sidebar-overlay').off('click').on('click', function() {
        $('.sidebar').removeClass('active');
        $('.sidebar-overlay').removeClass('active');
    });

    // 点击菜单项后关闭菜单（在移动端）
    $('.sidebar li').off('click.mobile').on('click.mobile', function() {
        if (window.innerWidth <= 768) {
            $('.sidebar').removeClass('active');
            $('.sidebar-overlay').removeClass('active');
        }
    });

    // 监听窗口大小变化
    $(window).off('resize.sidebar').on('resize.sidebar', function() {
        if (window.innerWidth > 768) {
            $('.sidebar').removeClass('active');
            $('.sidebar-overlay').removeClass('active');
        }
    });
}

function generateSidebar() {
    var sidebarHtml = config.apis.map(function(api, index) {
        return '<li class="flow ' + (index === 0 ? 'active' : '') + '" data-api-id="' + api.id + '">' + api.name + '</li>';
    }).join('');

    $('.sidebar').html(sidebarHtml);

    // 绑定点击事件
    $('.sidebar li').click(function() {
        var apiId = $(this).data('api-id');
        showApiDetails(apiId);
    });
}

function showApiDetails(apiId) {
    console.log("apiId", apiId);
    
    currentApi = config.apis.find(function(api) {
        return api.id === apiId;
    });
    if (!currentApi) return;

    // 更新侧边栏选中状态
    $('.sidebar li').removeClass('active');
    $('.sidebar li[data-api-id="' + apiId + '"]').addClass('active');

    // 更新标题
    $('.api-title').text(currentApi.name);

    // 生成并插入API内容
    var apiContent = generateApiContent(currentApi);
    $('#apiDetails').html(apiContent);

    console.log('currentApi', currentApi);
    console.log("apiResponses", apiResponses);
    

    // 检查是否有保存的响应数据
    if (apiResponses[apiId]) {
        var apiTestSection = $('#apiDetails').find('.api-test-section');
        var requestDataStr = JSON.stringify(apiResponses[apiId].request, null, 2);

        // 显示请求数据
        apiTestSection.find('.request-data').text(requestDataStr);
        
        // 如果是 getTaskStatus 页面
        if (currentApi.id === 'getTaskStatus') {
            console.log("getTaskStatus");
            
            // 创建响应表格
            var $responseSection = apiTestSection.find('.response-section');
            $responseSection.html(
                '<h4>响应数据</h4>' +
                '<div class="table-header">' +
                    '<button type="button" class="btn btn-danger clear-table-btn">清空表格</button>' +
                '</div>' +
                '<div class="response-table-container">' +
                '<table class="response-table">' +
                '<thead>' +
                '<tr>' +
                '<th>任务ID</th>' +
                '<th>状态</th>' +
                '<th>总文件数</th>' +
                '<th>已完成数</th>' +
                '<th class="progress-column">进度</th>' +
                '<th>开始时间</th>' +
                '<th>耗时</th>' +
                '<th>错误信息</th>' +
                '</tr>' +
                '</thead>' +
                '<tbody></tbody>' +
                '</table>' +
                '</div>' +
                '<pre class="response-data" style="display: none;"></pre>'
            );

            // 设置响应数据（隐藏的JSON格式）
            var responseDataStr = JSON.stringify(apiResponses[apiId].response, null, 2);
            $responseSection.find('.response-data').text(responseDataStr);

            // 更新表格数据，只显示来自 getTaskStatus 的查询
            var taskStatusResponses = {};
            var hasData = false;
            for (const taskId in apiResponses[apiId].response) {
                // 检查这个响应是否来自 getTaskStatus
                if (apiResponses[apiId].source === 'getTaskStatus' || taskStatusQueries.has(taskId)) {
                    const response = apiResponses[apiId].response[taskId];
                    addOrUpdateTableRow($responseSection.find('tbody'), taskId, response);
                    taskStatusResponses[taskId] = response;
                    hasData = true;
                }
            }


            // 绑定清空按钮事件
            $responseSection.find('.clear-table-btn').on('click', function() {
                if (confirm('确定要清空表格所有数据吗？')) {
                    // 清空表格
                    $responseSection.find('tbody').empty();
                    
                    // 清空隐藏的JSON数据
                    $responseSection.find('.response-data').text('{}');
                    
                    // 清空全局响应数据
                    apiResponses['getTaskStatus'] = {
                        request: {},
                        response: {},
                        timestamp: new Date().toLocaleString()
                    };

                    // 清空任务跟踪集合
                    taskStatusQueries.clear();

                    // 禁用清空按钮
                    $(this).prop('disabled', true);
                }
            });

            // // 更新表格数据
            // for (const taskId in apiResponses[apiId].response) {
            //     const response = apiResponses[apiId].response[taskId];
            //     addOrUpdateTableRow($responseSection.find('tbody'), taskId, response);
            // }
        } else {
            console.log("other");
            // 其他API页面显示普通的响应数据
            var responseDataStr = JSON.stringify(apiResponses[apiId].response, null, 2);
            console.log("responseDataStr", responseDataStr);
            apiTestSection.find('.response-data').text(responseDataStr);
            

            // 非轮询接口添加时间戳显示
            if (!apiTestSection.find('.response-timestamp').length) {
                apiTestSection.find('.response-data').after(
                    '<div class="response-timestamp">最后请求时间: ' +
                    apiResponses[apiId].timestamp + '</div>'
                );
            } else {
                apiTestSection.find('.response-timestamp').text(
                    '最后请求时间: ' + apiResponses[apiId].timestamp
                );
            }
        }

        // 如果有表单数据，填充表单
        if (apiResponses[apiId].request) {
            fillFormWithData(apiTestSection.find('form'), apiResponses[apiId].request);
        }
    }else{
        console.log("no-data");
        var apiTestSection = $('#apiDetails').find('.api-test-section');
        apiTestSection.find('.response-data').text('');
    }

    // 绑定表单事件
    bindFormEvents(currentApi);
}

// 添加填充表单数据的辅助函数
function fillFormWithData(form, data) {
    Object.keys(data).forEach(function(key) {
        var input = form.find('[name="' + key + '"]');
        if (input.length) {
            if (input.is('select')) {
                input.val(data[key]).trigger('change');
            } else {
                input.val(data[key]);
            }
        }
    });
}

// 事件处理相关函数
function bindFormEvents(api) {
    // 先解绑所有相关事件
    $(document).off('click', '.add-file-btn');
    $(document).off('click', '.remove-file-btn');
    $('.add-file-btn').off('click');
    $('.remove-file-btn').off('click');

    // TaskID 添加/删除功能
    if (api.id === 'getTaskStatus') {
        // 修改提交按钮处理
        $('.api-test-section .submit-btn').off('click').on('click', function(e) {
            e.preventDefault();
            var form = $(this).closest('form');

            // 获取任务ID
            var taskId = $('.taskid-entry input').val().trim();
            if (!taskId) return;

            var hasData = false;

             // 将此任务ID添加到跟踪集合中
            taskStatusQueries.add(taskId);


            // 清空输入框
            $('.taskid-entry input').val('');

            // 如果表格不存在，初始化表格
            var $responseSection = form.closest('.api-test-section').find('.response-section');
            if (!$responseSection.find('.response-table').length) {
                $responseSection.html(
                    '<h4>响应数据</h4>' +
                    '<div class="table-header">' +
                        '<button type="button" class="btn btn-danger clear-table-btn">清空表格</button>' +
                    '</div>' +
                    '<div class="response-table-container">' +
                    '<table class="response-table">' +
                    '<thead>' +
                    '<tr>' +
                    '<th>任务ID</th>' +
                    '<th>状态</th>' +
                    '<th>总文件数</th>' +
                    '<th>已完成数</th>' +
                    '<th class="progress-column">进度</th>' +
                    '<th>开始时间</th>' +
                    '<th>耗时</th>' +
                    '<th>错误信息</th>' +
                    '</tr>' +
                    '</thead>' +
                    '<tbody></tbody>' +
                    '</table>' +
                    '</div>' +
                    '<pre class="response-data" style="display: none;"></pre>'
                );

                // 恢复历史数据
                if (apiResponses['getTaskStatus'] && apiResponses['getTaskStatus'].response) {
                    var $tbody = $responseSection.find('tbody');
                    var responseData = apiResponses['getTaskStatus'].response;
                    Object.keys(responseData).forEach(function(taskId) {
                        taskStatusQueries.add(taskId); // 将历史任务ID添加到跟踪集合
                        addOrUpdateTableRow($tbody, taskId, responseData[taskId]);
                    });
                    // 更新隐藏的JSON数据
                    $responseSection.find('.response-data').text(JSON.stringify(responseData, null, 2));
                }
            }

            // 显示请求数据
            var requestDataStr = JSON.stringify({ taskID: taskId }, null, 2);
            form.closest('.api-test-section').find('.request-data').text(requestDataStr);

            // 为新的taskId添加初始行
            var $tbody = $responseSection.find('tbody');
            addOrUpdateTableRow($tbody, taskId, {
                status: '等待响应...',
                AllFileCunt: '-',
                DoneFileCunt: '-',
                BeginTime: '-',
                EndTime: '-',
                ErrInfo: '-',
                lastUpdateTime: new Date().toLocaleString()
            });

            // 启动新的轮询
            adndisk.taskPolling.startPolling(taskId, function(taskId, response) {
                // 确保在当前页面时才更新表格
                if (currentApi && currentApi.id === 'getTaskStatus' && taskStatusQueries.has(taskId)) {
                    var $tbody = $('.response-table tbody');
                    if ($tbody.length) {
                        // 更新表格行
                        var updatedResponse = Object.assign({}, response, {
                            lastUpdateTime: new Date().toLocaleString()
                        });
                        addOrUpdateTableRow($tbody, taskId, updatedResponse);

                        // 检查表格是否有数据并更新按钮状态
                        var hasData = $tbody.find('tr').length > 0;

                    }
                   // 更新隐藏的JSON数据
                    var $responseData = $('.response-data');
                    try {
                        var responseData = JSON.parse($responseData.text() || '{}');
                    } catch (e) {
                        responseData = {};
                    }
                    responseData[taskId] = Object.assign({}, response, {
                        lastUpdateTime: new Date().toLocaleString()
                    });

                    $responseData.text(JSON.stringify(responseData, null, 2));

                    // 保存到全局响应数据，合并而不是覆盖
                    if (!apiResponses[api.id]) {
                        apiResponses[api.id] = {
                            request: { taskID: taskId },
                            response: {},
                            timestamp: new Date().toLocaleString()
                        };
                    }
                    // 只更新当前任务的响应数据
                    apiResponses[api.id].response[taskId] = Object.assign({}, response, {
                        lastUpdateTime: new Date().toLocaleString()
                    });
                    apiResponses[api.id].timestamp = new Date().toLocaleString();
                
                }

                

                // if(!apiResponses["getTaskInfo"]) {
                //     var apiTestSection = $('#apiDetails').find('.api-test-section');
                //     apiTestSection.find('.response-data').text('');
                // }

                // 保存到全局响应数据
                // apiResponses[api.id] = {
                //     request: { taskID: taskId },
                //     response: responseData,
                //     timestamp: new Date().toLocaleString()
                // };
            });
        });


    } else {

        // 重新绑定提交按钮事件 - 修改选择器
        $('.api-test-section .submit-btn').off('click').on('click', function (e) {
            e.preventDefault();
            var form = $(this).closest('form');
            console.log('Submit button clicked');
            console.log('Current API:', api);

            // Clear previous errors
            form.find('.field-error').remove();
            form.find('.error').removeClass('error');

            var formData = adndisk.serializeFormToJson(form);
            console.log('Form data:', formData);

            if (api.id === "extractPrintInfo") {
                formData.authJson = base64Helper.encode(JSON.stringify(formData.authJson));
            }

            if (api.id === "setPrintInfo") {
                var files = [];
                for (var f in formData.files) {
                    files.push(formData.files[f]);
                }
                formData.files = files;
            }

            // 处理空值
            function convertToStrings(obj) {
                for (var key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        if (obj[key] === null || obj[key] === undefined) {
                            obj[key] = '';
                        } else if (typeof obj[key] === 'object') {
                            convertToStrings(obj[key]);
                        } else {
                            obj[key] = obj[key].toString();
                        }
                    }
                }
            }

            if (formData) {
                convertToStrings(formData);
            }

            // 显示请求数据
            var requestDataStr = JSON.stringify(formData, null, 2);
            form.closest('.api-test-section').find('.request-data').text(requestDataStr);

            if (!adndisk.validateForm(form)) {
                console.log('Form validation failed');
                return;
            }

            // 发送请求
            adndisk.jsonHandler(api.path, null, formData, function (response) {
                // 保存响应数据到全局对象
                apiResponses[api.id] = {
                    request: formData,
                    response: response,
                    timestamp: new Date().toLocaleString()
                };

                // 显示响应数据
                var responseDataStr = JSON.stringify(response, null, 2);
                form.closest('.api-test-section').find('.response-data').text(responseDataStr);

                // 处理响应数据
                if (response && response.code === 0 && response.data) {
                    if (api.id === 'extractPrintInfo') {
                        var extractedData = response.data;
                        if (extractedData.discJson) {
                            for (var key in extractedData.discJson) {
                                if (extractedData.discJson.hasOwnProperty(key)) {
                                    form.find('[name="discJson.' + key + '"]').val(extractedData.discJson[key]);
                                }
                            }
                        }
                        if (extractedData.files && extractedData.files.length > 0) {
                            var fileData = extractedData.files[0];
                            for (var key in fileData) {
                                if (fileData.hasOwnProperty(key)) {
                                    form.find('[name="files[0].' + key + '"]').val(fileData[key]);
                                }
                            }
                        }
                    } else if (api.id === 'setPrintInfo') {
                        if (response.data.success) {
                            showErrorMessage('打印信息设置成功');
                        }
                    }
                }
            });
        });

        // 文件添加/删除功能
        var $filesContainer = $('.files-container');
        if ($filesContainer.length) {
            $filesContainer.one('click', '.add-file-btn', function (e) {
                e.stopPropagation();

                var $lastEntry = $('.file-entry:last');
                var $newEntry = $lastEntry.clone();

                $newEntry.find('input').val('');
                $newEntry.find('select').prop('selectedIndex', 0);

                $newEntry.find('.remove-file-btn').show();
                $('.remove-file-btn').show();

                $lastEntry.after($newEntry);

                updateFileIndices();

                bindFormEvents(api);
            });
        }

        $(document).on('click', '.remove-file-btn', function (e) {
            e.stopPropagation();

            $(this).closest('.file-entry').remove();
            updateFileIndices();

            if ($('.file-entry').length === 1) {
                $('.remove-file-btn').hide();
            }
        });
    }
}

function updateFileIndices() {
    $('.file-entry').each(function(index) {
        var $entry = $(this);
        $entry.attr('data-index', index);

        // 更新所有输入框的 name 和 id
        $entry.find('input, select').each(function() {
            var $input = $(this);
            var oldName = $input.attr('name');
            var oldId = $input.attr('id');

            if (oldName) {
                // 更新 name 属性
                var newName = oldName.replace(/files\[\d+\]/, 'files[' + index + ']');
                $input.attr('name', newName);
            }

            if (oldId) {
                // 更新 id 属性
                var newId = oldId.replace(/_\d+_/, '_' + index + '_');
                $input.attr('id', newId);

                // 更新对应 label 的 for 属性
                $input.closest('.form-group').find('label').attr('for', newId);
            }
        });
    });
}

function bindGlobalEvents() {
    // 重置按钮点击事件
    $(document).on('click', '.white_btn[type="reset"]', function() {
        const form = $(this).closest('form');
        form[0].reset();
        // 清空显示区域
        $('.request-data, .response-data').empty();
    });
}

function showErrorMessage(message) {
    var errorDiv = $('<div>')
        .addClass('error-message')
        .html('<div class="error-content"><span class="error-icon">⚠</span><span class="error-text">' + message + '</span><span class="error-close">×</span></div>')
        .appendTo('body');

    // 添加关闭按钮事件
    errorDiv.find('.error-close').click(function() {
        errorDiv.fadeOut(function() {
            errorDiv.remove();
        });
    });

    // 自动消失
    setTimeout(function() {
        errorDiv.fadeOut(function() {
            errorDiv.remove();
        });
    }, 5000);
}

// Base64 编码/解码辅助函数
var base64Helper = {
    encode: function(str) {
        try {
            return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
                function toSolidBytes(match, p1) {
                    return String.fromCharCode('0x' + p1);
                }));
        } catch (e) {
            console.error('Base64编码失败:', e);
            return '';
        }
    },

    decode: function(str) {
        try {
            return decodeURIComponent(atob(str).split('').map(function(c) {
                return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
            }).join(''));
        } catch (e) {
            console.error('Base64解码失败:', e);
            return '';
        }
    }
};

// 页面加载完成后初始化
$(document).ready(function() {
    // 初始化API请求工具
    adndisk.init({
        baseUrl: window.location.origin
    });

    // // 添加线程使用进度条容器
    // $('body').prepend(
    //     '<div class="thread-status-container">' +
    //         '<div class="thread-progress-bar">' +
    //             '<div class="thread-progress"></div>' +
    //         '</div>' +
    //         '<div class="thread-status-text"></div>' +
    //     '</div>'
    // );

    // 开始自动轮询任务状态
    startThreadStatusPolling();

    // 使用事件委托绑定清空按钮事件
    $(document).off('click', '.clear-table-btn').on('click', '.clear-table-btn', function(e) {
        if ($(this).prop('disabled')) return;
        
        if (confirm('确定要清空表格所有数据吗？（正在进行的任务将保留）')) {
            var $responseSection = $(this).closest('.response-section');
            var apiTestSection = $responseSection.closest('.api-test-section');
            var $tbody = $responseSection.find('tbody');
            
            // 获取所有行的任务ID和状态
            var allTasks = [];
            $tbody.find('tr').each(function() {
                var taskId = $(this).find('td:first').text();
                var status = $(this).find('td:eq(1)').text(); // 获取状态列的值
                if (taskId) {
                    allTasks.push({ 
                        id: taskId, 
                        status: status
                    });
                }
            });

            // 筛选出要删除的任务（已完成、失败或等待中的任务）
            var tasksToRemove = allTasks.filter(task => 
            //     task.status === '已完成' || // 状态码 2
            //     task.status === '失败' ||   // 状态码 3
            //     task.status === '等待中'    // 状态码 0
            // );
            task.status === '已完成' || // 状态码 2
            task.status === '失败' ||  // 状态码 3
            task.status === '未知状态' // 状态码 0
        );

            // 从表格中移除这些任务的行
            tasksToRemove.forEach(task => {
                $tbody.find('tr').filter(function() {
                    return $(this).find('td:first').text() === task.id;
                }).remove();
                // 从轮询集合中移除已完成或失败的任务
                taskStatusQueries.delete(task.id);
            });

            // 更新隐藏的JSON数据，只保留进行中的任务
            var currentResponse = {};
            if (apiResponses['getTaskStatus'] && apiResponses['getTaskStatus'].response) {
                Object.entries(apiResponses['getTaskStatus'].response).forEach(([taskId, data]) => {
                    // 只保留状态为"进行中"的任务
                    if (data.status === '进行中' || data.status === '等待中') {
                        currentResponse[taskId] = data;
                    }
                });
            }

            // 更新全局响应数据
            apiResponses['getTaskStatus'] = {
                request: apiResponses['getTaskStatus']?.request || {},
                response: currentResponse,
                timestamp: new Date().toLocaleString()
            };

            // 更新隐藏的JSON数据
            $responseSection.find('.response-data').text(JSON.stringify(currentResponse, null, 2));

            // 如果没有任何数据了，禁用清空按钮
            var remainingRows = $tbody.find('tr').length;
            $(this).prop('disabled', remainingRows === 0);

            // 如果没有进行中的任务，清空请求数据显示
            if (Object.keys(currentResponse).length === 0) {
                apiTestSection.find('.request-data').text('');
            }

            console.log('Tasks in progress:', currentResponse);
            console.log('Removed tasks:', tasksToRemove);
        }
    });

    // 添加菜单按钮和遮罩层
    if (!$('.menu-toggle').length) {
        $('body').prepend('<button class="menu-toggle"><svg viewBox="0 0 24 24" width="24" height="24"><path fill="currentColor" d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"/></svg></button><div class="sidebar-overlay"></div>');
    }

    // 绑定菜单按钮点击事件
    $('.menu-toggle').off('click').on('click', function() {
        $('.sidebar').toggleClass('active');
        $('.sidebar-overlay').toggleClass('active');
    });

    // 点击遮罩层关闭菜单
    $('.sidebar-overlay').off('click').on('click', function() {
        $('.sidebar').removeClass('active');
        $('.sidebar-overlay').removeClass('active');
    });

    // 点击菜单项后关闭菜单（在移动端）
    $('.sidebar li').off('click.mobile').on('click.mobile', function() {
        if (window.innerWidth <= 768) {
            $('.sidebar').removeClass('active');
            $('.sidebar-overlay').removeClass('active');
        }
    });

    // 监听窗口大小变化
    $(window).off('resize.sidebar').on('resize.sidebar', function() {
        if (window.innerWidth > 768) {
            $('.sidebar').removeClass('active');
            $('.sidebar-overlay').removeClass('active');
        }
    });

    // 添加错误处理
    $(document).ajaxError(function(event, jqXHR, settings, error) {
        console.error('Ajax请求失败:', {
            url: settings.url,
            error: error,
            status: jqXHR.status
        });
    });

    // 加载配置
    try {
        loadConfig();
    } catch (error) {
        console.error('初始化失败:', error);
        showErrorMessage('系统初始化失败，请刷新页面重试');
    }

    // 绑定全局事件
    bindGlobalEvents();
});

// 侧边栏点击事件
$('.sidebar li').click(function() {
    // 移除所有 <li> 的 'active' 类
    $('.sidebar li').removeClass('active');
    // 给当前点击的 <li> 添加 'active' 类
    $(this).addClass('active');
});

// 修改表单提交处理
function handleFormSubmit(api, form) {
    var formData = {};
    var authJsonData = {
        file: {},
        code: ''
    };
    // 收集表单数据
    form.serializeArray().forEach(function(item) {
        if (item.name.indexOf('authJson.') === 0) {
            // 处理 authjson 相关的字段
            var parts = item.name.split('.');
            if (parts[1] === 'file') {
                authJsonData.file[parts[2]] = item.value;
            } else if (parts[1] === 'code') {
                authJsonData.code = item.value;
            }
        } else if (item.name.indexOf('.') !== -1) {
            // 处理其他嵌套字段
            var parts = item.name.split('.');
            var current = formData;
            for (var i = 0; i < parts.length - 1; i++) {
                if (!current[parts[i]]) {
                    current[parts[i]] = {};
                }
                current = current[parts[i]];
            }
            current[parts[parts.length - 1]] = item.value;
        } else {
            // 处理普通字段
            formData[item.name] = item.value;
        }
    });

    // 特殊处理 ExtractPrintInfo 接口的 authjson
    if (api.id === 'extractPrintInfo') {

        // 将 authJsonData 转换为 JSON 字符串，然后进行 base64 编码
        var authJsonStr = JSON.stringify(authJsonData);
        formData.authJson = btoa(unescape(encodeURIComponent(authJsonStr)));
    }

    // 发送请求
    $.ajax({
        url: api.path,
        type: api.method,
        contentType: 'application/json',
        data: JSON.stringify(formData),
        success: function(response) {
            showResponse(response);
        },
        error: function(xhr, status, error) {
            showError(error);
        }
    });
}

// 在页面卸载时清理所有轮询
$(window).on('unload', function() {
    adndisk.taskPolling.stopAllPolling();
});

// 添加更新表格行的辅助函数
function addOrUpdateTableRow($tbody, taskId, data) {
    var $existingRow = $tbody.find('tr[data-task-id="' + taskId + '"]');
    var statusText = getStatusText(data.status);
    
    var timeFormat = function(timestamp) {
        return timestamp && timestamp !== '-'
            ? new Date(parseInt(timestamp) * 1000).toLocaleString()
            : '-';
    };

    // 计算耗时
    var duration = '-';
    if (data.BeginTime && data.BeginTime !== '-') {
        var startTime = parseInt(data.BeginTime);
        var endTime = data.EndTime && data.EndTime !== '-'
            ? parseInt(data.EndTime)
            : Math.floor(Date.now() / 1000); // 如果未结束，使用当前时间

        if (!isNaN(startTime) && !isNaN(endTime)) {
            var seconds = endTime - startTime;
            if (seconds >= 0) {
                var hours = Math.floor(seconds / 3600);
                var minutes = Math.floor((seconds % 3600) / 60);
                var remainingSeconds = seconds % 60;

                var parts = [];
                if (hours > 0) parts.push(hours + '小时');
                if (minutes > 0) parts.push(minutes + '分');
                if (remainingSeconds > 0 || parts.length === 0) parts.push(remainingSeconds + '秒');

                duration = parts.join(' ');
            }
        }
    }

    // 计算进度
    var progress = '-';
    var progressPercent = 0;
    if (data.AllFileCunt && data.DoneFileCunt && data.AllFileCunt !== '-') {
        var total = parseInt(data.AllFileCunt);
        var done = parseInt(data.DoneFileCunt);
        if (!isNaN(total) && !isNaN(done) && total > 0) {
            progressPercent = Math.min(Math.round((done / total) * 100), 100);
            progress = progressPercent + '%';
        }
    }

    // 构建进度条HTML
    var progressBarHtml =
        '<div class="progress-bar-container">' +
        '<div class="progress-bar' + (data.status === '2' ? ' complete' : '') + '" style="width: ' + progressPercent + '%;">' +
        '<span class="progress-text">' + progress + '</span>' +
        '</div>' +
        '</div>';

    var rowHtml =
        '<td>' + taskId + '</td>' +
        '<td>' + statusText + '</td>' +
        '<td>' + (data.AllFileCunt || '-') + '</td>' +
        '<td>' + (data.DoneFileCunt || '-') + '</td>' +
        '<td class="progress-column">' + progressBarHtml + '</td>' +
        '<td>' + timeFormat(data.BeginTime) + '</td>' +
        '<td>' + duration + '</td>' +
        '<td class="error-info">' + (data.code !== "0" && data.msg || data.ErrInfo || '-') + '</td>';

    if ($existingRow.length) {
        $existingRow.html(rowHtml);
    } else {
        $tbody.append('<tr data-task-id="' + taskId + '">' + rowHtml + '</tr>');
    }
}

// 修改 getStatusText 函数，同时更新进度条状态
function getStatusText(status) {
    var text;
    switch(status) {
        case '0':
            text = '等待中';
            break;
        case '1':
            text = '进行中';
            break;
        case '2':
            text = '已完成';
            // 添加完成状态的类
            $('.progress-bar').addClass('complete');
            break;
        case '3':
            text = '失败';
            break;
        default:
            text = status || '未知状态';
    }
    return text;
    
}

// 添加验证函数
function validateTaskId(input) {
    const value = input.value.trim();
    const errorDiv = input.parentElement.nextElementSibling;
    const submitBtn = input.closest('form').querySelector('.submit-btn');

    if (!value) {
        input.classList.add('error');
        errorDiv.textContent = '请输入任务ID';
        submitBtn.disabled = true;
        return false;
    } else {
        input.classList.remove('error');
        errorDiv.textContent = '';
        // 检查所有taskID输入框是否都有值
        const allInputsValid = Array.from(document.querySelectorAll('input[name="taskID[]"]'))
            .every(input => input.value.trim());
        submitBtn.disabled = !allInputsValid;
        return true;
    }
}

// 添加线程状态轮询函数
function startThreadStatusPolling() {
    function updateThreadStatus() {
        $.ajax({
            url: '/GetTaskInfo',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ taskID: "123456789" }),
            success: function(response) {

                if (response.code == 0) {
                    const threadUsed = parseInt(response.ThreadUsedCont) || 0;
                    const maxThread = parseInt(response.MaxThreadCont) || 1;
                    const percentage = Math.min((threadUsed / maxThread) * 100, 100);
                    // 更新进度条
                    $('.thread-progress').css('width', percentage + '%');
                    $('.thread-status-text').text(
                        `线程使用情况: ${threadUsed}/${maxThread} (${percentage.toFixed(1)}%)`
                    );

                    // // 在 getTaskStatus 页面的 api-info 中更新线程状态
                    // if ($('.api-thread-status').length) {
                    //     $('.api-thread-status').text(
                    //         ` | 线程使用: ${threadUsed}/${maxThread} (${percentage.toFixed(1)}%)`
                    //     );
                    // }
                }
            },
            error: function(xhr, status, error) {
                console.error('获取线程状态失败:', error);
            }
        });
    }

    // 立即执行一次
    updateThreadStatus();
    // 每5秒更新一次
    setInterval(updateThreadStatus, 5000);
}

// 添加必要的样式
$('<style>')
    .text(`
        .thread-status-container {
            margin-bottom: 20px;
            background: #fff;
            padding: 10px;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            width: 100%;
        }
        .thread-progress-bar {
            background: #eee;
            height: 20px;
            border-radius: 10px;
            overflow: hidden;
            margin-bottom: 5px;
        }
        .thread-progress {
            height: 100%;
            background: #4CAF50;
            width: 0;
            transition: width 0.3s ease;
        }
        .thread-status-text {
            text-align: center;
            font-size: 12px;
            color: #666;
        }
        .input-container {
            display: flex !important;
            align-items: center !important;
        }
        .input-container input {
            flex-grow: 1 !important;
            margin-right: 0 !important;
        }
        .remove-taskid-btn {
            margin-left: 8px !important;
            padding: 4px 8px !important;
            background-color: #ff4d4f !important;
            color: white !important;
            border: none !important;
            border-radius: 4px !important;
            cursor: pointer !important;
            font-size: 12px !important;
            line-height: 1.5 !important;
            transition: background-color 0.3s !important;
        }
        .remove-taskid-btn:hover {
            background-color: #ff7875 !important;
        }
        .response-table .progress-column {
            width: 200px;
            min-width: 200px;
        }
        .progress-bar-container {
            width: 100%;
            background-color: #f5f5f5;
            border-radius: 4px;
            overflow: hidden;
        }
        .progress-bar {
            height: 20px;
            background-color: #4CAF50;
            text-align: center;
            line-height: 20px;
            color: white;
            transition: width 0.3s ease;
        }
        .progress-bar.complete {
            background-color: #52c41a;
        }
        .progress-text {
            position: relative;
            z-index: 1;
            color: #fff;
            text-shadow: 0 1px 2px rgba(0,0,0,0.2);
            font-size: 12px;
        }
    `)
    .appendTo('head');
